package com.lhfeiyu.action.front.forum;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Assets;
import com.lhfeiyu.config.Const;
import com.lhfeiyu.config.Page;
import com.lhfeiyu.domain.base.AliyunOSS;
import com.lhfeiyu.po.base.BaseAnnouncement;
import com.lhfeiyu.po.base.BaseApply;
import com.lhfeiyu.po.base.BaseForum;
import com.lhfeiyu.po.base.BaseForumArticle;
import com.lhfeiyu.po.base.BaseForumMember;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.service.AuthCheckService;
import com.lhfeiyu.service.base.BaseAnnouncementService;
import com.lhfeiyu.service.base.BaseApplyService;
import com.lhfeiyu.service.base.BaseDictService;
import com.lhfeiyu.service.base.BaseForumArticleService;
import com.lhfeiyu.service.base.BaseForumMemberService;
import com.lhfeiyu.service.base.BaseForumService;
import com.lhfeiyu.service.base.BasePictureService;
import com.lhfeiyu.service.base.BaseUserService;
import com.lhfeiyu.thirdparty.wx.business.AuthAccess;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.Check;
import com.lhfeiyu.tools.base.Result;

@Controller
public class ForumAction {

	@Autowired
	private BaseForumService forumService;
	@Autowired
	private BaseApplyService applyService;
	@Autowired
	private BaseForumArticleService forumArticleService;
	@Autowired
	private BaseForumMemberService forumMemberService;
	@Autowired
	private BaseAnnouncementService announcementService;
	@Autowired
	private BaseDictService dictService;
	@Autowired
	private AuthCheckService authCheckService;
	@Autowired
	private BaseUserService userService;
	@Autowired
	BasePictureService pictureService;

	private static Logger logger = Logger.getLogger("R");
	
	@RequestMapping(value = "/forumIndex")
	public ModelAndView forumIndex(ModelMap modelMap, HttpServletRequest request,
			@RequestParam(required = false) String r) {
		String path = Page.forumIndex;
		try {
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if (null == sessionUser) {
				String jumpUrl = "/forumIndex";
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			modelMap.put("user", sessionUser);
			json.put("user", sessionUser);
			modelMap.put("paramJson", json);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName() + "/forumIndex", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	@RequestMapping(value = "/forum/{forumId}")
	public ModelAndView forum(ModelMap modelMap, HttpServletRequest request, 
			@PathVariable Integer forumId,
			@RequestParam(required = false) String r) {
		String path = Page.forum;
		try {
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseForum forums = forumService.selectByPrimaryKey(forumId);

			json.put("forumId", forumId);
			//System.out.println(forums.getName());
			modelMap.addAttribute("forums", forums);
			modelMap.put("paramJson", json);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName() + "/forum" + "/" + forumId, modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@ResponseBody
	@RequestMapping(value = "/getForum", method = RequestMethod.POST)
	public JSONObject getForum(HttpServletRequest request, ModelMap modelMap,
			@RequestParam Integer forumId) {
		JSONObject json = new JSONObject();
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			if(Check.isNull(forumId)){
				return Result.failure(json, "123", "forumId_null");
			};
			map.put("id", forumId);
			
		    BaseForum forum = forumService.selectByCondition(map);
		    if(null == forum){
				return Result.failure(json, "345", "forum_null");
			};
			json.put("forum", forum);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName() + "/getForumArticleList", json);
		} 
		return Result.success(json);
	}
	

	@RequestMapping(value = "/forums")
	public ModelAndView forums(ModelMap modelMap, HttpSession session,
			@RequestParam(required = false, value = "typeId") Integer typeId, @RequestParam(required = false) String r,
			HttpServletRequest request) {
		String path = Page.frontForum;
		try {
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			/*
			 * User sessionUser = ActionUtil.checkSession4User(session); if(null
			 * == sessionUser){ String jumpUrl = "/forum"; if(null !=
			 * typeId)jumpUrl = "/forum?typeId="+typeId; return
			 * Result.userSessionInvalid(modelMap, jumpUrl); }
			 */
			if (null != typeId && !"".equals(typeId)) {
				modelMap.put("typeId", typeId);
			}
		} catch (Exception e) {
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载论坛页面出现异常_" + e.getMessage());
		}
		return new ModelAndView(path, modelMap);
	}

//	@RequestMapping(value = "/addForum")
//	public ModelAndView addForum(ModelMap modelMap, HttpSession session, @RequestParam(required = false) String r,
//			HttpServletRequest request) {
//		String path = Page.addForum;
//		try {
//			JSONObject json = new JSONObject();
//			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
//			BaseUser sessionUser = ActionUtil.checkSession4User(session);
//			if (null == sessionUser) {
//				String jumpUrl = "/addForum";
//				if (null != r)
//					jumpUrl += "?r=" + r;
//				return Result.userSessionInvalid(modelMap, jumpUrl);
//			}
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("parentId", 1);
//			List<BaseDict> dictForumList = dictService.selectListByCondition(map);
//			/*
//			 * if(null != articleId && !"".equals(articleId)){ ForumArticle
//			 * forumArticle = forumArticleService.selectByPrimaryKey(articleId);
//			 * modelMap.put("forumArticle", forumArticle); }
//			 */
//			modelMap.put("dictForumList", dictForumList);
//		} catch (Exception e) {
//			e.printStackTrace();
//			path = Page.error;
//			logger.error("LH_ERROR_加载添加申请论坛详情页面出现异常_" + e.getMessage());
//		}
//		return new ModelAndView(path, modelMap);
//	}

	@RequestMapping(value = "/forumRule")
	public ModelAndView forumRule(ModelMap modelMap, HttpSession session, @RequestParam(required = false) String r,
			HttpServletRequest request) {
		String path = Page.forumRule;
		try {
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(session);
			if (null == sessionUser) {
				String jumpUrl = "/forumRule";
				if (null != r)
					jumpUrl += "?r=" + r;
				return Result.userSessionInvalid(modelMap, jumpUrl);
			}
			Integer userId = sessionUser.getId();
			BaseUser user = userService.selectByPrimaryKey(userId);
			if (user.getIsRealAuth() != null && !"".equals(user.getIsRealAuth())) {
				if (user.getIsRealAuth() == 2) {
					modelMap.put("isRealAuth", "true");
				}
			} else {
				modelMap.put("isRealAuth", "false");
			}
		} catch (Exception e) {
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载论坛规则说明页面出现异常_" + e.getMessage());
		}
		return new ModelAndView(path, modelMap);
	}

	/** 论坛规则详情页面 */
	@RequestMapping(value = "/forumRuleAndAnnouncementList/{forumId}")
	public ModelAndView forumRuleAndAnnouncementList(ModelMap modelMap, HttpSession session,
			@PathVariable Integer forumId, @RequestParam(required = false) String r, HttpServletRequest request) {
		String path = Page.forumRuleAndAnnouncementList;
		try {
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			/*
			 * User sessionUser = ActionUtil.checkSession4User(session); if(null
			 * == sessionUser){ return Result.userSessionInvalid(modelMap,
			 * "/forumRuleAndAnnouncementList?forumId="+forumId); }
			 */
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", forumId);
			List<BaseForum> forumList = forumService.selectListByCondition(map);
			if (forumList.size() > 0) {
				map.clear();
				map.put("forumId", forumId);
				Integer count = forumArticleService.selectCountByCondition(map);
				BaseForum forum = forumList.get(0);
				modelMap.put("forum", forum);
				modelMap.put("count", count);
				List<BaseAnnouncement> announcementList = announcementService.selectListByCondition(map);
				modelMap.put("announcementList", announcementList);
			}
		} catch (Exception e) {
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载论坛规则详情页面出现异常_" + e.getMessage());
		}
		return new ModelAndView(path, modelMap);
	}

	/** 论坛规则详情页面 */
	@RequestMapping(value = "/forumRuleDetail")
	public ModelAndView forumRuleDetail(ModelMap modelMap, HttpSession session,
			@RequestParam(required = false, value = "forumId") Integer forumId,
			@RequestParam(required = false, value = "announcementTypeId") Integer announcementTypeId,
			@RequestParam(required = false) String r, HttpServletRequest request) {
		String path = Page.forumRuleDetail;
		try {
			/*
			 * User sessionUser = ActionUtil.checkSession4User(session); if(null
			 * == sessionUser){ return Result.userSessionInvalid(modelMap,
			 * "/forumRuleDetail?forumId="+forumId); }
			 */
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			Map<String, Object> map = new HashMap<String, Object>();
			if (null != forumId && !"".equals(forumId)) {
				map.put("id", forumId);
				List<BaseForum> forumList = forumService.selectListByCondition(map);
				if (forumList.size() > 0) {
					map.clear();
					map.put("forumId", forumId);
					Integer count = forumArticleService.selectCountByCondition(map);
					BaseForum forum = forumList.get(0);
					modelMap.put("forum", forum);
					modelMap.put("count", count);
				}
			}
			if (null != announcementTypeId && !"".equals(announcementTypeId)) {
				map.clear();
				map.put("typeId", announcementTypeId);
				List<BaseAnnouncement> announcementList = announcementService.selectListByCondition(map);
				if (announcementList.size() > 0) {
					BaseAnnouncement announcement = announcementList.get(0);
					modelMap.put("announcement", announcement);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载论坛规则详情页面出现异常_" + e.getMessage());
		}
		return new ModelAndView(path, modelMap);
	}
	
	
	//TODO 社区导航action
	//我的圈子
	@RequestMapping(value = "/myForumSquare")
	public ModelAndView myForumSquare(ModelMap modelMap, HttpServletRequest request) {
		String path = Page.myForumSquare;
		try {
			JSONObject json = new JSONObject();
			modelMap.put("paramJson", json);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName() + "/ForumSquare", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	//圈子广场
	@RequestMapping(value = "/forumSquare")
	public ModelAndView forumSquare(ModelMap modelMap, HttpServletRequest request) {
		String path = Page.forumSquare;
		try {
			JSONObject json = new JSONObject();
			modelMap.put("paramJson", json);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName() + "/ForumSquare", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	//热门圈子
	@RequestMapping(value = "/hotForumSquare")
	public ModelAndView hotForumSquare(ModelMap modelMap, HttpServletRequest request) {
		String path = Page.hotForumSquare;
		try {
			JSONObject json = new JSONObject();
			
			modelMap.put("paramJson", json);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName() + "/ForumSquare", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}

	@ResponseBody
	@RequestMapping(value = "/getForumList", method = RequestMethod.POST)
	public JSONObject getForumList(HttpServletRequest request,ModelMap modelMap) {
		List<BaseForum> forumList = null;
		JSONObject json = new JSONObject();
		try {
			Map<String, Object> map = ActionUtil.getAllParam(request);
			forumList = forumService.selectListByCondition(map);
			modelMap.put("paramJson", json);
			for (BaseForum baseForum : forumList) {
				//System.out.println(baseForum.getName());
			}
			Integer total = forumService.selectCountByCondition(map);
			Result.gridData(forumList, total, json);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName() + "/getForumList", json);
		}
		return Result.success(json);
	}
	
	//论坛申请页面
	@RequestMapping(value = "/forumApply")
	public ModelAndView forumApply(ModelMap modelMap, HttpServletRequest request,
			@RequestParam(required = false) String r) {
		String path = Page.forumApply;
		try {
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if (null == sessionUser) {
				String jumpUrl = "/forumApply";
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			modelMap.put("user", sessionUser);
			json.put("user", sessionUser);
			
			//微信验证
			String ticket = AuthAccess.getWxDataFromProperty("ticket");//从Property文件中获取ticket,如果文件中没有，则会远程获取
			String url = "http://weipaike.net/forumApply";
			url = ActionUtil.buildPromoterUrl(url, r);
			modelMap = AuthAccess.getSign(modelMap, ticket, url);
			
			modelMap.put("paramJson", json);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName() + "/forumApply", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	//论坛申请
	@ResponseBody
	@RequestMapping(value = "/addForum", method = RequestMethod.POST)
	public JSONObject addForum(HttpServletRequest request,ModelMap modelMap,
			@ModelAttribute BaseApply apply) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = user.getId();
			String username = user.getUsername();
			Date date = new Date();
			
			String forumName = apply.getAttr1();
			BaseForum baseForum = forumService.selectByName(forumName);
			if(null == baseForum){
			Map<String, Object> map = ActionUtil.getAllParam(request);
			apply.setUserId(userId);
			apply.setApplyType(2);
			apply.setCreatedAt(date);
			apply.setCreatedBy(username);
			apply.setMainStatus(1);//
			
			//TODO 论坛申请测试 （默认通过审核）
			BaseForum forum = new BaseForum();
			
			String basePath = request.getServletContext().getRealPath("/");
			String filePaths = apply.getFile1();
			
			//System.out.println("圈子申请图片地址filePaths： "+filePaths);
			
			String endpoint = Const.oss_endpoint;
		    String accessKeyId = Const.oss_accessKeyId;
		    String accessKeySecret = Const.oss_accessKeySecret;
		    String bucketName = Const.oss_bucketName;
		    String bucketEndpoint = Const.oss_bucketEndpoint;
		    AliyunOSS oss = AliyunOSS.buildOSS(null, null, endpoint, accessKeyId, accessKeySecret, bucketName, bucketEndpoint);
			String mediaId = filePaths;
			if(Check.isNotNull(mediaId) && !mediaId.equalsIgnoreCase("undefined")){//此处为微信服务器获取用户上传的图片
			    json = pictureService.getPicPathsByWxServerIds(json, mediaId, basePath, oss);
				String picPaths = json.getString("picPaths");
				if(Check.isNotNull(picPaths)){
					if(picPaths.startsWith(","))picPaths = picPaths.substring(1);
					String localPath = "/file/wx/" + picPaths.substring(picPaths.lastIndexOf("/"), picPaths.length());
					apply.setFile1(picPaths);
					apply.setFile2(localPath);
					
				}
			}
			applyService.insert(apply);
			
			
			
			if(Check.isNull(forum.getLogo())){
				forum.setLogo(Assets.defaultForumLogo);
			}
			
			
			forum.setLogo(apply.getFile1());
			forum.setName(apply.getAttr1());
			forum.setOwnerId(userId);
			forum.setCreatedBy(username);
			forum.setModeratorId(userId);
			forum.setSubModeratorId(userId);
			
//			forumService.insertSelective(forum);
			
			BaseForumMember baseForumMember = new BaseForumMember();
			baseForumMember.setForumId(forum.getId());
			baseForumMember.setUserId(userId);
//			forumMemberService.insertSelective(baseForumMember);
			}else{
				return Result.failure(json, "论坛名已存在", "The Forum Name is exist");
			}
			modelMap.put("paramJson", json);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName() + "/addForum", json);
		}
		//System.out.println(json);
		return Result.success(json);
	}

	@ResponseBody
	@RequestMapping(value="/forumIndexs/{forumId}")
	public ModelAndView forumUserArticle(ModelMap modelMap,HttpServletRequest request,
			@PathVariable Integer forumId,
			@RequestParam(required=false) String r) {
		String path = Page.forumIndexs;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("forumId", forumId);
			
			if (null == sessionUser) {
				String jumpUrl = "/forumIndexs"+forumId;
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			
			map.put("sessionUsersId", sessionUser.getId());
			BaseForum forum = forumService.selectByPrimaryKeyAndIsJoin(map);
			if(null != forum){
				//BaseForumArticle forumArticle = forumArticleService.selectListByCondition(forum.getId());
				modelMap.put("user", sessionUser);
				modelMap.put("forum", forum);
				json.put("forum", forum);
				json.put("user", sessionUser);
				if((sessionUser.getId() == forum.getModeratorId())||(sessionUser.getId() == forum.getSubModeratorId())){
					modelMap.put("isManager", 1);
				}
			}
			modelMap.put("paramJson", json);
		}catch(Exception e){
			Result.catchError(e, logger, this.getClass().getName() + "/forumIndex/", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}



}
